package org.langqiao.io.encrypt;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * 功能：对文件加密解密操作
 * @author YMY
 */
public class FileEncryplmpl implements FileEncryptInterface {
	 
	/**
	 * 功能：加密文件
	 */
	public boolean DESEncrypt(Key key, String FileName){
		boolean result = false;
		StringBuffer sb = null;
		try{
			/*
			 * Cipher类无构造方法，调用getInstance()方法将所请求转换的名称传递给它 参数为 转换的名称，例如
			 * DES/CBC/PKCS5Padding，这里我们使用DES转换。
			 */
			Cipher encriptCipher = Cipher.getInstance("DES");
			// 用密钥初始化此 Cipher
			encriptCipher.init(Cipher.ENCRYPT_MODE, key);
			FileInputStream in = new FileInputStream(FileName);
			int size = in.available();
			byte[] encode = new byte[size];
			in.read(encode);
			String srcCode = new String(encode);
			// 按单部分操作加密数据
			byte[] desCode = encriptCipher.doFinal(srcCode.getBytes());
			// 将加密后的数据转换成16进制的字符串返回
			sb = new StringBuffer(desCode.length * 2);
			for (int i = 0; i < desCode.length; i++){
				int temp = desCode[i];
				// 把负数转换为正数
				if (temp < 0){
					temp = temp + 256;// byte的最小值为-256,最大值为255
				}
				// 小于 0F 的数需要在前面补0
				if (temp < 16){
					sb.append("0");
				}
				sb.append(Integer.toString(temp, 16));
			}
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileName)));
			out.write(sb.toString(), 0, sb.length());
			out.close();
			result = true;
	  }catch (NoSuchAlgorithmException e){
		  e.printStackTrace();
	  }catch (NoSuchPaddingException e){
		  e.printStackTrace();
	  }catch (InvalidKeyException e){
		  e.printStackTrace();
	  }catch (IllegalBlockSizeException e){
		  e.printStackTrace();
	  }catch (IOException e){
		  e.printStackTrace();
	  }catch (BadPaddingException e){
		  e.printStackTrace();
	  }
	  return result;
	}
	
	 /**
	  * 功能：解密文件
	  */
	public boolean DESDecrypt(String FileName, Key key){
		Cipher decriptCipher = null;
		String decriptString = null;
		boolean result = false;
		try{
			FileInputStream in = new FileInputStream(FileName);
			int size = in.available();
			byte[] encode = new byte[size];
			in.read(encode);
			String encriptCode = new String(encode);
	
			byte[] encriptByte = encriptCode.getBytes();
	
			byte[] decriptByte = new byte[encriptByte.length / 2];
			for (int i = 0; i < encriptByte.length; i += 2){
				String strTmp = new String(encriptByte, i, 2);
				decriptByte[i / 2] = (byte) Integer.parseInt(strTmp, 16);
			}
			decriptCipher = Cipher.getInstance("DES");
			decriptCipher.init(Cipher.DECRYPT_MODE, key);
	
			byte[] outByte = decriptCipher.doFinal(decriptByte);
			decriptString = new String(outByte);
	
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileName)));
			out.write(decriptString.toString(), 0, decriptString.length());
			out.close();
	    }catch (NoSuchAlgorithmException e) {
	    	e.printStackTrace();
	    }catch (NoSuchPaddingException e) {
	    	e.printStackTrace();
	    }catch (InvalidKeyException e) {
	    	e.printStackTrace();
	    }catch (IllegalBlockSizeException e) {
	    	e.printStackTrace();
	    }catch (BadPaddingException e){
	    	System.out.println("密钥错误！");
	    	e.printStackTrace();
	    }catch (IOException e){
	    	e.printStackTrace();
	    }
	    return result;
	}
	
	/**
	 * 自定义一个key
	 */
	public Key getKey(String keyRule){
		Key key = null;
		byte[] keyByte = keyRule.getBytes();
		// 创建一个空的八位数组,默认情况下为0
		byte[] byteTemp = new byte[8];
		// 将用户指定的规则转换成八位数组
		for (int i = 0; i < byteTemp.length && i < keyByte.length; i++){
			byteTemp[i] = keyByte[i];
		}
		key = new SecretKeySpec(byteTemp, "DES");
		return key;
	}
	
	/**
	 * 第二种产生key的方法
	 */
	 public Key getKey2(){
		 Key key = null;
		 // 创建一个可信任的随机数源，DES算法需要
		 SecureRandom sr = new SecureRandom();
		 try{
			 // 用DES算法创建一个KeyGenerator对象
			 KeyGenerator kg = KeyGenerator.getInstance("DES");
			 // 初始化此密钥生成器,使其具有确定的密钥长度
			 kg.init(sr);
			 // 生成密匙
			 key = kg.generateKey();
		 }catch (NoSuchAlgorithmException e){
			 e.printStackTrace();
		 }
		 return key;
	 }
}






